# @Time    : 2020/8/24 17:43
# @Author  : Del Fung
# @File    : read_files.py
# @Software: PyCharm
# @Time    : 2020/8/18 14:40
# @Author  : Del Fung
# @File    : read_files.py
# @Software: PyCharm

import yaml
import configparser
from pathlib import Path

__all__ = ['read_yamls', 'read_yaml', 'read_inis', 'read_ini', 'read_excel']


def read_yaml(file_path):
    """
    单个yaml文件读取，结果返回成字典格式
    :param file_path: （必须），文件路径，比如：D:xx/cc/config.yaml
    :return: {'a':'123','b':'234'}
    """
    try:
        return yaml.safe_load(open(file_path, 'r', encoding='utf-8'))
    except Exception as e:
        raise e


def read_yamls(folder_path):
    """
    读取一个文件夹下的所有yaml文件
    :param folder_path:（必须） 文件目录路径：比如：D:/aa/cc
    :return:{a:{admin:123},b:{admin:234}}
    """
    _path = Path(folder_path)
    _data_dict = dict()
    try:
        for _file_path in _path.glob(r'*.yaml'):
            if _file_path:
                _data_dict.update(read_yaml(_file_path))
        return _data_dict
    except Exception as e:
        raise e


def read_ini(file_path):
    """
    读取ini文件，结果返回成自动格式
    :param file_path: （必须） 文件路径，比如：D:xx/cc/config.yaml
    :return: {'a':'123','b':'234'}
    """
    try:
        parser = configparser.RawConfigParser()
        parser.read(file_path, 'utf-8')
        if parser.sections():
            return {par: dict(parser.items(par)) for par in parser.sections()}
        else:
            raise FileNotFoundError(f'[Errno 2] No such file or directory: {file_path}')
    except Exception as e:
        raise e


def read_inis(folder_path):
    """
    读取一个文件夹下的所有ini文件
    :param folder_path:（必须） 文件目录路径：比如：D:/aa/cc
    :return:{'a':'123','b':'234'}
    """
    _path = Path(folder_path)
    _data_dict = dict()
    try:
        for _file_path in _path.glob(r'*.ini'):
            if _file_path:
                _data_dict.update(read_ini(_file_path))
        return _data_dict
    except Exception as e:
        raise e


def read_excel(file_path):
    import pandas as pd
    cases_heap = list()
    data_frame = pd.read_excel(file_path, dtype='str').fillna('').replace('\n', '', regex=True)
    data_frame.apply(lambda x: cases_heap.append(x.to_dict()), axis=1)
    return cases_heap
